﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net.Mime;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Resources;

namespace CI.UI.Prototypes
{
    public class EveIconConverter : IValueConverter
    {


        static T LoadResource<T>(string path)
        {

            var c = default(T);

            //TODO:REPLACE WITH USING

            var sri = Application.GetResourceStream(new Uri(path, UriKind.Relative));



            if (sri.ContentType == "application/xaml+xml")
            {
                
                c = (T)XamlReader.Load(sri.Stream);

            }

            else if (sri.ContentType.IndexOf("image") >= 0)
            {

                BitmapImage bi = new BitmapImage();

                bi.BeginInit();

                bi.StreamSource = sri.Stream;

                bi.EndInit();

                if (typeof(T) == typeof(ImageSource))
                {
                    c = (T)((object)bi);
                }

                else if (typeof(T) == typeof(MediaTypeNames.Image))
                {

                    var img = new Image {Source = bi};

                    c = (T)((object)img);
                }

            }



            sri.Stream.Close();

            sri.Stream.Dispose();



            return c;

        }

        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            // value should be an int
            var graphicID = value is int ? (int) value : 0;

            var graphic = App.GraphicRepository.Get(graphicID);

            if (graphic == null) return null;
            if (string.IsNullOrEmpty(graphic.Icon)) return null;

            // create a brush with the image from eveIcons...

            //var bmp = new BitmapImage(new Uri("pack://application:,,,/Prototypes;eveIcons/icon" + graphic.icon + ".png", UriKind.RelativeOrAbsolute));
            //var img = new BitmapImage();
            var c = new ImageBrush
                        {
                            ImageSource = LoadResource<ImageSource>("eveIcons/icon" + graphic.Icon + ".png"),
                            TileMode = TileMode.None,
                            Stretch = Stretch.None
                        };

            return c;
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}
